package com.jzo2o.customer.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.api.publics.MapApi;
import com.jzo2o.api.publics.dto.response.LocationResDTO;
import com.jzo2o.common.constants.HeaderConstants;
import com.jzo2o.common.expcetions.CommonException;
import com.jzo2o.common.model.CurrentUserInfo;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.*;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.mapper.CommonUserMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.domain.CommonUser;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {

    @Resource
    private CommonUserMapper commonUserMapper;

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity(Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery()
                .eq(AddressBook::getUserId, userId)
                .eq(AddressBook::getCity, city)
                .list();
        if(CollUtils.isEmpty(addressBooks)) {
            return new ArrayList<>();
        }
        return BeanUtils.copyToList(addressBooks, AddressBookResDTO.class);
    }

    //n("查询地址簿信息")
    @Override
    public PageResult<AddressBook> findAddressBook(HttpServletRequest request, AddressBookPageQueryReqDTO addressBookPageQueryReqDTO) {
//        Long pageNo = addressBookPageQueryReqDTO.getPageNo();
//        Long pageSize = addressBookPageQueryReqDTO.getPageSize();
//        Boolean isAsc1 = addressBookPageQueryReqDTO.getIsAsc1();
//        String orderBy1 = addressBookPageQueryReqDTO.getOrderBy1();
//        Boolean isAsc2 = addressBookPageQueryReqDTO.getIsAsc2();
//        String orderBy2 = addressBookPageQueryReqDTO.getOrderBy2();
        //拿到请求头中的 当前 user信息
        String userInfo = request.getHeader(HeaderConstants.USER_INFO);
        if(userInfo==null){
            throw new CommonException("用户未登录，请登录");
        }
        String decodeUserInfo = Base64Utils.decodeStr(userInfo);
        //拿到当前登录的用用户信息
        CurrentUserInfo currentUserInfo = JsonUtils.toBean(decodeUserInfo, CurrentUserInfo.class);

        Long userid = currentUserInfo.getId();

        Page<AddressBook> addressBookPage = PageUtils.parsePageQuery(addressBookPageQueryReqDTO, AddressBook.class);
        QueryWrapper<AddressBook> wrapper  =new QueryWrapper<>();
        wrapper.eq("user_id",userid);

        Page<AddressBook> addressBookPage1 = baseMapper.selectPage(addressBookPage, wrapper);


        return PageUtils.toPage(addressBookPage1, AddressBook.class);
    }

    //编辑地址回显数据")
    @Override
    public AddressBook getAddressBook(Long id) {

        AddressBook addressBook = baseMapper.selectById(id);
        return addressBook;
    }

    //("设置默认地址 1默认  0 非默认")
    @Override
    public AddressBook defaultAddress(Long id, int flag) {
        AddressBook addressBook = baseMapper.selectById(id);
        if (addressBook ==null){
            throw new CommonException("该地址簿不存在");
        }
        //只能有一个默认地址，
        //先将该用户的地址全部改为 非默认 ，然后再 将需要默认的地址更新
        lambdaUpdate().eq(AddressBook::getUserId,addressBook.getUserId())
                .set(AddressBook::getIsDefault,0)
                .update();

        boolean update = lambdaUpdate().eq(AddressBook::getId, id)
                .set(AddressBook::getIsDefault, flag).update();
        if (!update){
            throw new CommonException("设置默认值失败");
        }
        AddressBook addressBook2 = baseMapper.selectById(id);

        return addressBook2;
    }

    //编辑地址信息更新")
    @Override
    public AddressBook updateAddress(Long id,AddressBook addressBook) {
        AddressBook addressBook1 = baseMapper.selectById(id);
        if (ObjectUtil.isNull(addressBook1)){
            throw new CommonException("该地址不存在");
        }
        //判断is_default 是否为默认 如果是默认地址  先将该用户所有地址的 is_default全设为 0
        if (addressBook.getIsDefault()==1){
            lambdaUpdate().eq(AddressBook::getUserId,addressBook1.getUserId())
                    .set(AddressBook::getIsDefault,0)
                    .update();
        }

        QueryWrapper<AddressBook> wrapper =new QueryWrapper<>();
        wrapper.eq("id",id);
        int update = baseMapper.update(addressBook, wrapper);
        if (update<1){
            throw new CommonException("地址簿更新失败");
        }

        AddressBook addressBook2 = baseMapper.selectById(id);

        return addressBook2;
    }



//================================      // 删除地址")=================================
    // n("删除地址")
    @Override
    public void delete(String[] ids) {

        if (ObjectUtil.isNull(ids)){
            throw new CommonException("删除失败，无id");
        }

        List<String> idslist = new ArrayList<>();
        for (String id : ids ){
            idslist.add(id);
        }

        int i = baseMapper.deleteBatchIds(idslist);
        if (i<1){
            throw new CommonException("删除失败");
        }
    }

//================================= //("添加地址簿信息")===================================
    //("添加地址簿信息")
    @Override
    public void addAddressBook(HttpServletRequest request, AddressBookUpsertReqDTO addressBookUpsertReqDTO) {

        String userInfo = request.getHeader(HeaderConstants.USER_INFO);
        if (StringUtils.isEmpty(userInfo)){
            throw new CommonException("用户未登录，请登录再添加地址");
        }
        String decodeUserInfo = Base64Utils.decodeStr(userInfo);

        //拿到当前登录的用用户信息
        CurrentUserInfo currentUserInfo = JsonUtils.toBean(decodeUserInfo, CurrentUserInfo.class);
        //location   "117.30794,31.79322"
        String location = addressBookUpsertReqDTO.getLocation();
        String[] split = location.split(",");
        String lon =split[0]; //"117.30794"
        String lat =split[1];  //"31.79322"
        Double dLon =new Double(lon); //字符串转double  117.30794
        Double dLat =new Double(lat); //               31.79322
        AddressBook addressBook = new AddressBook();
        BeanUtil.copyProperties(addressBookUpsertReqDTO,addressBook);
        addressBook.setLon(dLon);
        addressBook.setLat(dLat);
        //将当前登录的用户id 存储再addressBook对象中
        addressBook.setUserId(currentUserInfo.getId());

        //添加地址
        int insert = baseMapper.insert(addressBook);
        if (insert<1){
            throw new CommonException("添加地址失败");
        }


    }




}
